﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Engine.Dtd.Schema;
using System.Diagnostics;

namespace Engine.Sgml.Parser {
    internal sealed class WhiteSpaceReader : IElementReader {
        private StringBuilder builder;

        public WhiteSpaceReader(StringBuilder builder) {
            Guard.ArgumentNotNull(builder, "builder");
            this.builder = builder;
            }

        public SElement Read(SgmlStreamReader reader, SElement parent, Context context) {
            builder.Clear();
            do {
                builder.Append(reader.CurrentChar);
                reader.ReadChar();
                } while (XmlConvert.IsWhitespaceChar(reader.CurrentChar));

            SElement whitespace = parent.Nodes.Push();
            whitespace.Clear();
            whitespace.Parent = parent;
            whitespace.LineNumber = context.LineNumber;
            whitespace.LinePosition = context.LinePosition;
            whitespace.Name = DName.PCData.ToString();
            whitespace.DName = InclusionNode.Instance.Name;
            whitespace.NodeType = SgmlNodeType.WhiteSpace;
            whitespace.Value = builder.ToString();
            builder.Clear();

            SgmlNodeType nodeType = SgmlParser.IsText(reader.CurrentChar, parent);
            if (nodeType != SgmlNodeType.None) {
                IElementReader elementReader = context.Readers[nodeType];
                return elementReader.Read(reader, parent, context);
                }
            else {
                return whitespace;
                }
            }
        }
    }
